#include "core/main.h"

double SparseDoubleVector::operator[](int i) const
{
    if (_data.count(i) == 0) return 0;
    return _data.find(i)->second;
}

void SparseDoubleVector::print() const
{
    for (auto it = _data.begin(); it != _data.end(); ++it) {
        cout << it->first << ": " << it->second << endl;
    }
}

void SparseDoubleVector::set(int i, double val) {
    _data[i] = val;
}

void SparseDoubleVector::operator*=(double val)
{
    auto it = _data.begin();
    while (it != _data.end()) {
        it->second = val * it->second;
        if (-_epsilon < it->second && it->second < _epsilon) {
            _data.erase(it++);
        } else {
            ++it;
        }
    }
    /*
    for (auto it = _data.begin(); it != _data.end(); ++it) {
        it->second = val * it->second;
    }
    */
}

void SparseDoubleVector::filter(double c, vector<double> &v) const
{
    for (auto it = _data.begin(); it != _data.end(); ++it)
    {
        int i = it->first;
        double d = it->second;
        if (i < (int)v.size()) {
            v[i] += c * d;
        }
    }
}

void SparseDoubleVector::cleanup(double epsilon)
{
    auto it = _data.begin();
    while (it != _data.end()) {
        if (it->second < epsilon) {
            _data.erase(it++);
        } else {
            ++it;
        }
    }
}